<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <div>
      <el-card>
        <div>
          <el-row :gutter="25">
            <el-col :span="8">
              <el-input
                v-model="queryInfo.query"
                placeholder="请输入内容"
                clearable
                @clear="getUserList"
              >
                <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
              </el-input>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="addDialogVisiable = true">添加用户</el-button>
            </el-col>
          </el-row>
        </div>
        <div>
          <el-table :data="userList" border stripe>
            <el-table-column type="index" label="#" align="center"></el-table-column>
            <el-table-column label="姓名" prop="username" align="center"></el-table-column>
            <el-table-column label="邮箱" prop="email" align="center"></el-table-column>
            <el-table-column label="手机" prop="mobile" align="center"></el-table-column>
            <el-table-column label="角色" prop="role_name" align="center"></el-table-column>
            <el-table-column label="状态" align="center">
              <template v-slot="scope">
                <el-switch v-model="scope.row.mg_state" @change="UserStateChange(scope.row)"></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200">
              <template v-slot="scope">
                <el-row>
                  <el-button
                    type="success"
                    round
                    size="small"
                    @click="showEditDialog(scope.row.id)"
                  >
                    <i class="el-icon-edit"></i>
                  </el-button>
                  <el-button type="danger" round size="small" @click="delUserById(scope.row.id)">
                    <i class="el-icon-delete"></i>
                  </el-button>
                  <el-tooltip
                    class="item"
                    effect="light"
                    content="分配角色"
                    placement="top"
                    :enterable="false"
                  >
                    <el-button type="warning" round size="small" @click="setRoleDialog(scope.row)">
                      <i class="el-icon-setting"></i>
                    </el-button>
                  </el-tooltip>
                </el-row>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum"
            :page-sizes="[1, 2, 5, 10]"
            :page-size="queryInfo.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-card>
      <!-- 添加用户对话框 -->
      <el-dialog title="添加用户" :visible.sync="addDialogVisiable" width="50%" @close="addDialogClose">
        <el-form
          :model="addUserForm"
          :rules="addUserFormRules"
          ref="addUserFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password" show-password></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisiable = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑用户 -->
      <el-dialog title="编辑用户信息" :visible.sync="editDialogVisiable" width="50%">
        <el-form
          :model="editUserForm"
          :rules="addUserFormRules"
          ref="editUserFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editUserForm.username" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisiable = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog title="分配角色" :visible.sync="setRoleDialogVisiable" width="50%" @close="setRoleDialogClose">
        <p>用户名称：{{userinfo.username}}</p>
        <p>用户角色：{{userinfo.role_name}}</p>
        <p>分配新的角色：
          <el-select v-model="setRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleDialogVisiable = false">取 消</el-button>
          <el-button type="primary" @click="setRole">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱！"));
    };
    var checkMobile = (rule, value, cb) => {
      const regEmail = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号！"));
    };

    return {
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 10,
      },
      userList: [],
      total: 0,
      addDialogVisiable: false,
      //添加用户表单
      addUserForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      editDialogVisiable: false,
      editUserForm: {
        username: "",
        email: "",
        mobile: "",
      },
      //添加用户表单验证
      addUserFormRules: {
        username: [
          { required: true, message: "请输入用户名", tigger: "blur" },
          { min: 3, max: 10, message: "用户名长度3~10个字符", tigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", tigger: "blur" },
          { min: 3, max: 15, message: "用户名长度3~15个字符", tigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", tigger: "blur" },
          { validator: checkEmail, tigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", tigger: "blur" },
          { min: 11, max: 11, message: "请输入11位手机号", tigger: "blur" },
          { validator: checkMobile, tigger: "blur" },
        ],
      },
      //分配角色对话框是否显示
      setRoleDialogVisiable: false,
      //需要分配角色的用户
      userinfo: {},
      //所有角色列表
      rolesList: [],
      //新分配的角色id
      setRoleId: '',
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("获取用户列表失败！");
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    handleSizeChange(newSize) {
      console.log(newSize);
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      console.log(newPage);
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    async UserStateChange(userInfo) {
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );
      if (res.meta.status != 200) {
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.error("更新用户状态失败！");
      } else {
        this.$message.success("更新用户状态成功！");
      }
    },
    //添加用户对话框关闭事件
    addDialogClose() {
      this.$refs.addUserFormRef.resetFields();
    },
    //添加用户方法
    addUser() {
      this.$refs.addUserFormRef.validate(async (cb) => {
        if (cb == false) return;
        const { data: res } = await this.$http.post("users", this.addUserForm);
        console.log(res);
        if (res.meta.status != 201)
          return this.$message.error("添加用户失败！" + res.meta.msg);
        this.$message.success("添加用户成功！");
        this.$refs.addUserFormRef.resetFields();
        this.addDialogVisiable = false;
        this.getUserList();
      });
    },
    //编辑用户弹窗
    async showEditDialog(id) {
      this.editDialogVisiable = true;
      const { data: res } = await this.$http.get("users/" + id);
      console.log(res);
      if (res.meta.status != 200)
        return this.$message.error("获取用户信息失败，请刷新页面！");
      this.editUserForm = res.data;
      console.log(this.editUserForm);
    },
    editUser() {
      this.$refs.editUserFormRef.validate(async (callback) => {
        if (callback == false) return;
        const { data: res } = await this.$http.put(
          "users/" + this.editUserForm.id,
          {
            email: this.editUserForm.email,
            mobile: this.editUserForm.mobile,
          }
        );
        if (res.meta.status != 200)
          return this.$message.error("更新数据失败！");
        //关闭窗口
        this.editDialogVisiable = false;
        //刷新列表
        this.getUserList();
        //更新成功
        this.$message.success("更新用户信息成功！");
      });
    },
    async delUserById(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      console.log(confirmResult);
      if (confirmResult != "confirm") return this.$message.info("已取消操作");
      const { data: res } = await this.$http.delete("users/" + id);
      if (res.meta.status != 200) return this.success.error("删除用户失败！");
      this.$message.success("删除用户成功！");
      this.getUserList();
    },
    async setRoleDialog(userinfo) {
      this.userinfo = userinfo;
      console.log(userinfo);
      const {data: res} = await this.$http.get('roles');
      if(res.meta.status !== 200) return this.$message.error('获取角色列表失败！');
      this.rolesList = res.data;
      this.setRoleDialogVisiable = true;
    },
    async setRole(){
      if(!this.setRoleId) return this.$message.info('未选择角色！');
      const {data: res} = await this.$http.put(`users/${this.userinfo.id}/role`,{rid: this.setRoleId})
      if(res.meta.status != 200) return this.$message.error('更新用户角色失败！');
      this.setRoleDialogVisiable = false;

      this.$message.success('分配角色成功！');
    },
    //关闭分配角色Dialog清空角色id
    setRoleDialogClose(){
      this.setRoleId = ''
    }
  },
};
</script>

<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 15px;
}
function .el-card {
  box-shadow: 0 0 1 0 rgb(0, 0, 0.15) !important;
}
.el-table {
  margin-top: 20px;
  font-size: 12px;
}
.el-pagination {
  margin-top: 15px;
}
</style>